package com.ty.config;

import cn.hutool.core.util.ObjectUtil;
import com.ty.interceptor.TraceIdFeignInterceptor;
import feign.Logger;
import feign.Request;
import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.concurrent.TimeUnit;

import static com.alibaba.nacos.api.common.Constants.TOKEN;

@Configuration
@Slf4j
public class FeignConfig {

    @Bean
    public Logger.Level logLevel(){
        return Logger.Level.FULL;
    }

   // @Bean
    public Request.Options options() {
        return new Request.Options(10L, TimeUnit.SECONDS, 6L,TimeUnit.SECONDS,false);
    }

    //@Bean
    public RequestInterceptor traceIdFeignInterceptor() {
        return new TraceIdFeignInterceptor();
    }
    private static final String TRACE_ID = "traceId";
    private static final String TOKEN = "token";

    @Bean
    public RequestInterceptor traceIdFeignInterceptor2() {
        return (requestTemplate -> {

            String traceId = MDC.get(TRACE_ID);
            requestTemplate.header("traceId", traceId);
            ServletRequestAttributes attributes =(ServletRequestAttributes)(RequestContextHolder.getRequestAttributes());
            String token = attributes.getRequest().getHeader(TOKEN);
            if(ObjectUtil.isNotEmpty(token)){
                requestTemplate.header(TOKEN, token);
                log.debug("把token带过去了,token:{}",token);
            }
        });
    }
}
